package com.dfy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dfy.dto.LoginRequest;
import com.dfy.dto.LoginResponse;
import com.dfy.dto.RegisterRequest;
import com.dfy.dto.UpdateUserRequest;
import com.dfy.entity.User;
import com.dfy.common.Result;
import com.dfy.service.UserService;
import com.dfy.exception.BusinessException;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import com.dfy.util.JwtUtils;
import com.dfy.mapper.UserMapper;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import com.dfy.dto.SpotDTO;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/register")
    public Result<User> register(@Validated @RequestBody RegisterRequest request) {
        log.info("收到注册请求，参数：{}", request);
        User user = userService.register(request);
        log.info("注册成功，用户信息：{}", user);
        return Result.success(user);
    }

    @PostMapping("/login")
    public Result<LoginResponse> login(@Validated @RequestBody LoginRequest request) {
        log.info("收到登录请求手机号：{}", request.getPhone());
        LoginResponse response = userService.login(request);
        return Result.success(response);
    }

    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Long id) {
        // 这里应该调用 Service 层查询用户
        return Result.success(new User());
    }

    @PutMapping("/{id}")
    public Result<?> updateUser(@PathVariable Long id, 
                              @Validated @RequestBody UpdateUserRequest request) {
        log.info("收到更新用户请求，用户ID：{}，参数：{}", id, request);
        
        // 获取当前登录用户
        String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
        String currentUserRole = SecurityContextHolder.getContext()
                .getAuthentication()
                .getAuthorities()
                .stream()
                .findFirst()
                .map(a -> a.getAuthority())
                .orElse("");
        
        // 检查是否有权限修改
        if (!currentUserId.equals(String.valueOf(id)) && !currentUserRole.equals("ROLE_ADMIN")) {
            return Result.error(403, "无权修改其他用户信息");
        }
        
        userService.updateUser(id, request);
        return Result.success("用户信息更新成功");
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteUser(@PathVariable Long id) {
        // 这里应该调用 Service 层删除用户
        return Result.success("用户删除成功");
    }

    @GetMapping
    public Result<Page<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String phone) {
        
        int offset = (current - 1) * size;
        
        // 获取用户列表
        List<User> users = userMapper.findUserList(username, email, phone, offset, size);
        
        // 获取总数
        long total = userMapper.countUserList(username, email, phone);
        
        // 创建分页对象
        Page<User> page = new Page<>(current, size, total);
        page.setRecords(users);
        
        return Result.success(page);
    }

    @PostMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        // 直接返回成功，因为我们使用的是无状态JWT
        return Result.success(null);
    }

    @GetMapping("/{userId}/favorites/exists/{spotId}")
    @PreAuthorize("isAuthenticated()")
    public Result<Boolean> checkFavorite(
            @PathVariable Long userId,
            @PathVariable Long spotId) {
        // 获取当前登录用户
        String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
        
        // 验证用户是否在查询自己的收藏
        if (!userId.toString().equals(currentUserId)) {
            throw new BusinessException(403, "无权查看其他用户的收藏状态");
        }
        
        boolean exists = userService.checkFavorite(userId, spotId);
        return Result.success(exists);
    }

    @PostMapping("/{userId}/favorites/{spotId}")
    @PreAuthorize("isAuthenticated()")
    public Result<String> addFavorite(
            @PathVariable Long userId,
            @PathVariable Long spotId) {
        // 获取当前登录用户
        String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
        
        // 验证用户是否在操作自己的收藏
        if (!userId.toString().equals(currentUserId)) {
            throw new BusinessException(403, "无权操作其他用户的收藏");
        }
        
        userService.addFavorite(userId, spotId);
        return Result.success("收藏成功");
    }

    @DeleteMapping("/{userId}/favorites/{spotId}")
    @PreAuthorize("isAuthenticated()")
    public Result<String> removeFavorite(
            @PathVariable Long userId,
            @PathVariable Long spotId) {
        // 获取当前登录用户
        String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
        
        // 验证用户是否在操作自己的收藏
        if (!userId.toString().equals(currentUserId)) {
            throw new BusinessException(403, "无权操作其他用户的收藏");
        }
        
        userService.removeFavorite(userId, spotId);
        return Result.success("取消收藏成功");
    }

    @GetMapping("/{userId}/favorites")
    @PreAuthorize("isAuthenticated()")
    public Result<List<SpotDTO>> getFavorites(@PathVariable Long userId) {
        // 获取当前登录用户
        String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
        
        // 验证用户是否在查询自己的收藏
        if (!userId.toString().equals(currentUserId)) {
            throw new BusinessException(403, "无权查看其他用户的收藏");
        }
        
        List<SpotDTO> favorites = userService.getFavorites(userId);
        return Result.success(favorites);
    }
} 